package jjn.round1;

/**
 * 变体三：查找第一个大于等于给定值的元素
 *
 * @author Jjn
 * @link {<a href="https://time.geekbang.org/column/article/42733">16 | 二分查找（下）：如何快速定位IP对应的省份地址？</a>}
 * @since 2022-08-06 16:44
 */
public class AlgorithmColumn16_BinarySearchVariation3 {
    
    public int search(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (nums[mid] < target) {
                low = mid + 1;
            } else {
                if (mid == 0 || nums[mid - 1] < target) {
                    return mid;
                } else {
                    high = mid - 1;
                }
            }
        }
        return -1;
    }
}
